package zx.x.modules.yshbms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zx.x.common.utils.R;
import zx.x.modules.app.utils.BeanUtils;
import zx.x.modules.yshapp.entity.RaffleEntity;
import zx.x.modules.yshapp.entity.RaffleSignUpUserEntity;
import zx.x.modules.yshapp.entity.RaffleSpecialNameListEntity;
import zx.x.modules.yshbms.dto.RaffleDto;
import zx.x.modules.yshbms.service.RaffleService;
import zx.x.modules.yshbms.service.RaffleSignUpUserService;
import zx.x.modules.yshbms.service.RaffleSpecialNameListService;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 抽奖
 */
@RestController
@RequestMapping("yshbms/raffle")
public class RaffleController {
    @Autowired
    private RaffleService raffleService;

    @Autowired
    private RaffleSpecialNameListService raffleSpecialNameListService;

    @Autowired
    private RaffleSignUpUserService raffleSignUpUserService;

    /**
     * 新建抽奖
     */
    @RequestMapping("/save")
    @Transactional
    public R save(@RequestBody RaffleDto raffleDto) {
        RaffleEntity raffleEntity = new RaffleEntity();
        BeanUtils.copyProperties(raffleDto, raffleEntity);
        raffleEntity.setCjTime(new Date());
        raffleEntity.setIsOpen(0);
        raffleService.save(raffleEntity);
        if (raffleDto.getRaffleSpecialNameListEntities() != null && raffleDto.getRaffleSpecialNameListEntities().size() > 0) {
            for (int i = 0; i < raffleDto.getRaffleSpecialNameListEntities().size(); i++) {
                raffleDto.getRaffleSpecialNameListEntities().get(i).setRaffleId(raffleEntity.getId());
            }
            raffleSpecialNameListService.saveBatch(raffleDto.getRaffleSpecialNameListEntities());
        }
        return R.ok();
    }

    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody RaffleDto raffleDto) {

        raffleService.updateById(raffleDto);

        //先删
        Map<String, Object> map = new HashMap<>();
        map.put("raffle_id", raffleDto.getId());
        raffleSpecialNameListService.removeByMap(map);
        //后加
        if (raffleDto.getRaffleSpecialNameListEntities() != null && raffleDto.getRaffleSpecialNameListEntities().size() > 0) {
            for (int i = 0; i < raffleDto.getRaffleSpecialNameListEntities().size(); i++) {
                raffleDto.getRaffleSpecialNameListEntities().get(i).setRaffleId(raffleDto.getId());
            }
            raffleSpecialNameListService.saveBatch(raffleDto.getRaffleSpecialNameListEntities());
        }

        return R.ok();
    }

    @RequestMapping("/list")
    public R list(RaffleEntity raffleEntity) {

        Page page = PageHelper.startPage(raffleEntity.getPage(), raffleEntity.getLimit());
        return R.ok().put("page", raffleService.raffeList(raffleEntity)).put("pages", page.getPages()).put("total", page.getTotal());
    }

    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        RaffleDto raffleDto = new RaffleDto();
        RaffleEntity raffleEntity = raffleService.getById(id);
        if (raffleEntity != null) {
            BeanUtils.copyProperties(raffleEntity, raffleDto);
            List<RaffleSpecialNameListEntity> raffleSpecialNameListEntities
                    = raffleSpecialNameListService
                    .list(new QueryWrapper<RaffleSpecialNameListEntity>().eq("raffle_id", raffleEntity.getId()));
            raffleDto.setRaffleSpecialNameListEntities(raffleSpecialNameListEntities);
        }
        return R.ok().put("raffleDto", raffleDto);
    }

    @Scheduled(fixedRate = 1000 * 120)
    public void lottery() {

        List<RaffleEntity> raffleEntities = raffleService.list(new QueryWrapper<RaffleEntity>()
                .eq("is_open", 0)
                .le("open_time", new Date()));
        if (raffleEntities != null && raffleEntities.size() > 0) {
            //中奖名单
            for (int i = 0; i < raffleEntities.size(); i++) {
                //内定名单
                List<RaffleSpecialNameListEntity> raffleSpecialNameListEntities
                        = raffleSpecialNameListService
                        .list(new QueryWrapper<RaffleSpecialNameListEntity>()
                                .eq("raffle_id", raffleEntities.get(i).getId()));
                if (raffleSpecialNameListEntities != null && raffleSpecialNameListEntities.size() > 0) {
                    //内的名单中奖
                    for (int j = 0; j < raffleSpecialNameListEntities.size(); j++) {
                        RaffleSignUpUserEntity raffleSignUpUserEntity = new RaffleSignUpUserEntity();
                        raffleSignUpUserEntity.setIsWin(0);
                        UpdateWrapper<RaffleSignUpUserEntity> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("raffle_id", raffleEntities.get(i).getId());
                        updateWrapper.eq("user_id", raffleSpecialNameListEntities.get(j).getUserId());
                        raffleSignUpUserService.update(raffleSignUpUserEntity, updateWrapper);
                    }


                }
                //非内定（随机中奖）
                Integer prizeNum = raffleEntities.get(i).getPrizeNum()-raffleSpecialNameListEntities.size();
                if(prizeNum>0){
                    List<RaffleSignUpUserEntity> raffleSignUpUserEntityList = raffleSignUpUserService
                            .list(new QueryWrapper<RaffleSignUpUserEntity>()
                                    .eq("raffle_id", raffleEntities.get(i).getId())
                                    .eq("is_win", 1));//参与抽奖名单.且除去内定名单
                    if(raffleSignUpUserEntityList!=null&&raffleSignUpUserEntityList.size()>0){
                        Random random = new Random();
                        List<Integer> randomNumbers = new ArrayList<>();
                        while (randomNumbers.size()<prizeNum){
                            // 生成 随机整数
                            int num = random.nextInt(raffleSignUpUserEntityList.size());
                            // 检查生成的数字是否已经在列表中，如果不在则添加到列表
                            if (!randomNumbers.contains(num)) {
                                randomNumbers.add(num);
                            }
                        }
                        for (int j = 0; j < randomNumbers.size(); j++) {
                            RaffleSignUpUserEntity rsuue= raffleSignUpUserEntityList.get(randomNumbers.get(j));
                            rsuue.setIsWin(0);
                            raffleSignUpUserService.updateById(rsuue);
                        }
                    }

                    RaffleEntity raffleEntity = new RaffleEntity();
                    raffleEntity.setId(raffleEntities.get(i).getId());
                    raffleEntity.setIsOpen(1);
                    raffleService.updateById(raffleEntity) ;
                    System.out.println("抽奖结束");
                }

            }

        }
    }

}
